package com.test.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.test.model.Person;
import com.test.service.Impl.PersonServiceImpl;


@Controller 
public class PersonController {

    @Autowired  
    private PersonServiceImpl personService; 
	
	@ModelAttribute
	public void getPerson(String id, Model model) {
		if (!StringUtils.isBlank(id)) {
			Person person = personService.getPersonById(id);
			model.addAttribute("person", person);
		} else {
			model.addAttribute("person", new Person());
		}
	}
    
    /**  
     * 分页获取人员列表
     */  
    @RequestMapping("/getPersonList")  
    public String getFriendstPage(Model model,int page,int size,String identityNumber,@RequestParam("personName")String personName,
    		String sex,@RequestParam("birthTime")String birthTime) throws ParseException{  
		Page<Person> pages = personService.getPersonListByConditions(identityNumber, personName, sex, birthTime, page, size);
		List<Person> personlist = pages.getContent();
		long element = pages.getTotalElements();//记录条数
		int pageAmount = pages.getTotalPages();//页数
    	System.out.println(personName);
    	model.addAttribute("element", element);  
    	model.addAttribute("pageAmount", pageAmount);  
    	model.addAttribute("personlist", personlist);  
    	model.addAttribute("page",page);
    	model.addAttribute("size",size);
    	model.addAttribute("personName",personName);
    	model.addAttribute("sex",sex);
    	model.addAttribute("birthTime",birthTime);
    	model.addAttribute("identityNumber",identityNumber);
    	return "index";  
   }  
    
    /**  
     * 根据ID查人员信息
     */  
    @RequestMapping("/updatePerson")  
    public String updatePerson(String id,Model model){
    	Person person = personService.getPersonById(id);
    	model.addAttribute("person", person);
        return "increasePerson";  
    }  
    
    /**  
     * 新增
     */  
    @RequestMapping( value = "/addPerson", method = RequestMethod.POST)  
    public String addPerson(@ModelAttribute("person") Person person,
    		@RequestParam("birthTime")String birthTime,@RequestParam("identityNumber")String identityNumber) {
        		String birthTime2 = birthTime.replace("-", "");//去掉-符号方便与身份证对比
        		Date d1=new Date();//获取当前时间
//       		System.out.println(person.getPersonName());
//        		String birthTime2 = "";//数组变字符串
//                for(int i=0;i<bt.length;i++){
//                	birthTime2 = birthTime2+bt[i];
//                }
        		person.setCreateTime(d1);
        		person.setLastUpdateTime(d1);
                String in = identityNumber.substring(6, 14);//与身份证的6到14位对比
                if(birthTime2.equals(in)){
                	personService.savePerson(person);
                	return "addSuccess";  
                }else{
                	return "idOrBirthTimeError";  
                }
    }
    /*
     * 更新数据
     */
    @RequestMapping( value = "/updatePerson", method = RequestMethod.POST)  
    public String UpdatePerson(@ModelAttribute("person") Person person,
    		@RequestParam("birthTime")String birthTime,@RequestParam("identityNumber")String identityNumber) {
        		String birthTime2 = birthTime.replace("-", "");//去掉-符号方便与身份证对比
        		Date d1=new Date();//获取当前时间
//       		System.out.println(person.getPersonName());
//        		String birthTime2 = "";//数组变字符串
//                for(int i=0;i<bt.length;i++){
//                	birthTime2 = birthTime2+bt[i];
//                }
        		person.setLastUpdateTime(d1);
                String in = identityNumber.substring(6, 14);//与身份证的6到14位对比
                if(birthTime2.equals(in)){
                	personService.savePerson(person);
                	return "index";  
                }else{
                	return "idOrBirthTimeError";  
                }
    }
    
    /**  
     * 根据ID查人员信息
     */  
    @RequestMapping("/seePerson")  
    public String seePerson(String id,Model model){
    	Person person = personService.getPersonById(id);
    	model.addAttribute("person", person);
        return "personMessage";  
    }  
    
    
    /**  
     * 根据身份证号码删除人员
     */  
    @RequestMapping("/deleteemployee")  
    @ResponseBody
    public void deletePerson(String id){
    	Person person = personService.getPersonById(id);
    	personService.deletePerson(person);
    }	
    
    /**  
     * 判断身份证号码是否唯一
     */  
    @RequestMapping("/validateIDCard")
    @ResponseBody
    public String validateIDCard(String id,String identityNumber) throws IOException{
    	boolean result;
    	if(StringUtils.isBlank(id)){
    		Person person = personService.getOneByIdentityNumber(identityNumber);
	        if(person == null){
	        	result = true;
	        }else{
	        	result = false;
	        }
    	}else{
    		Person person = personService.getOneByIdentityNumber(identityNumber);
    		Person Person2 = personService.getOneByIdentityNumberAndId(identityNumber, id); 
    		if((person==null)||(person!=null&&Person2!=null)){
    			result = true;
    		}else{
    			result = false;
    		}
    	} 
        Map<String, Boolean> map = new HashMap<>();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }
    
    /**  
     * 用来判断出生日期是否晚于当前日期
     */  
    @RequestMapping("/validateBirthTime")
    @ResponseBody
    public String validateBirthTime(String birthTime) throws  ParseException, IOException{
    	boolean result;
    	Date date = new Date();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
    	Date d = sdf.parse(birthTime);
    	boolean flag = d.before(date);			//判断出生日期是否在当前时间之前
    	if(flag){
        	result = true;
        }else{
        	result = false;
        }
        Map<String, Boolean> map = new HashMap<>();
        map.put("valid", result);
        ObjectMapper mapper = new ObjectMapper();
        String resultString = "";
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }    
}
